package programagraficos;

import java.awt.Color;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.jfree.chart.*;
import org.jfree.chart.axis.*;
import org.jfree.chart.labels.StandardXYSeriesLabelGenerator;
import org.jfree.chart.labels.XYToolTipGenerator;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.XYBarRenderer;
import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;
import org.jfree.data.time.*;
import org.jfree.data.xy.IntervalXYDataset;
import org.jfree.data.xy.XYDataset;
import org.jfree.ui.ApplicationFrame;
import org.jfree.ui.RefineryUtilities;

public final class ProgramaGraficos extends ApplicationFrame implements ChartMouseListener, KeyListener {

    private static int mesClicado, diaClicado, horaClicada;
    private ChartPanel chartPanel;
    private boolean dataVelha = false;
    private boolean primeiroClick = true;
    private static boolean mes = true;
    private static boolean dia = false;
    private static boolean hora = false;
    private static boolean minuto = false;
    private static Conexao conexao;
    private static int idAlicate;
    private static String alicateNome;
    private static int anoAtual;
    private static Calendar calendar;
    private static ProgramaGraficos demo;
    private static XYPlot plot;
    private static IntervalXYDataset intervalxydataset;
    private static TimeSeriesCollection timeseriescolletion;
    private static TimeSeries seriesMes, serieDia, serieHora, serieMinuto;
    private static JFreeChart chart;
    private static boolean timeSeriesSendoUsado = false;
    private static XYBarRenderer xYBarRenderer;
    private static double tarifaLuz;
    private static boolean corrente = true;
    private static boolean potencia = false;
    private static boolean moeda = false;
    private static int numeroLinhas;
    private static double maiorValorMes, maiorValorHora, maiorValorMinuto, maiorValorDia;

    public IntervalXYDataset getIntervalxyDataset() {
        return intervalxydataset;
    }

    public Calendar getCalendar() {
        return calendar;
    }

    public ProgramaGraficos(String title, TimeSeries timeSeries) throws SQLException {
        super(title);
        chart = createChart(timeseriescolletion);
        chartPanel = new ChartPanel(chart, false);
        chartPanel.setPreferredSize(new java.awt.Dimension(990, 270));
        chartPanel.addChartMouseListener(this);
        chartPanel.setMouseZoomable(true);
        addKeyListener(this);
        setContentPane(chartPanel);
        Timer timer = new Timer();
        TimerTask timerTask = new TimerTask() {

            @Override
            public void run() {
                atualizarSeries();
                try {
                    this.finalize();
                } catch (Throwable ex) {
                    Logger.getLogger(ProgramaGraficos.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        };
        timer.scheduleAtFixedRate(timerTask, 60000, 60000);
        tarifaLuz = 0.37035;
        ResultSet rst = conexao.selectFromWhere("select id from leituras where sensor_id = " + idAlicate);
        rst.last();
        numeroLinhas = rst.getInt("id");
    }

    public TimeSeriesCollection getTimeSeriesCollection() {
        return timeseriescolletion;
    }

    public double getTarifa() {
        return tarifaLuz;
    }

    private static JFreeChart createChart(IntervalXYDataset dataset) {
        chart = ChartFactory.createXYBarChart("", "Mês", true, "corrente (A)", dataset, PlotOrientation.VERTICAL, false, true, false);
        chart.setBackgroundPaint(Color.white);
        plot = (XYPlot) chart.getPlot();
        plot.setBackgroundPaint(Color.white);
        plot.setDomainGridlinePaint(Color.gray);
        plot.setRangeGridlinePaint(Color.gray);
        plot.getRenderer().setSeriesToolTipGenerator(0, new XYToolTipGenerator() {

            @Override
            public String generateToolTip(XYDataset xyd, int i, int i1) {
                DecimalFormat df = new DecimalFormat("0.00");
                return "" + df.format((xyd.getYValue(i, i1)));
            }
        });
        xYBarRenderer = (XYBarRenderer) plot.getRenderer();
        DateTickUnit unit = new DateTickUnit(DateTickUnitType.MONTH, 1);
        TickUnits units = new TickUnits();
        units.add(unit);
        plot.getDomainAxis().setStandardTickUnits(units);
        DateAxis dateaxis = (DateAxis) plot.getDomainAxis();
        dateaxis.setTickMarkPosition(DateTickMarkPosition.MIDDLE);
        plot.getRangeAxis().setAutoRange(false);
        plot.getDomainAxis().setAutoRange(false);
        return chart;
    }

    public static void createDataset() {
        timeseriescolletion.addSeries(seriesMes);
        timeseriescolletion.addSeries(serieDia);
        timeseriescolletion.addSeries(serieHora);
        timeseriescolletion.addSeries(serieMinuto);
    }

    public static void atualizarSeries() {
        try {
            ResultSet rst = conexao.selectFromWhere("select id from leituras where sensor_id = " + idAlicate);
            rst.last();
            System.out.println("select id from leituras where sensor_id = " + idAlicate);
            System.out.println("rst.getInt(id): " + rst.getInt("id"));
            System.out.println("numeroLinhas: " + numeroLinhas);
            if (rst.getInt("id") > numeroLinhas) {
                System.out.println("Medidas novas");
                rst = conexao.selectFromWhere("select valor, Data,Hora from leituras where sensor_id = " + idAlicate + " && id > " + numeroLinhas);
                System.out.println("select valor, Data, Hora from leituras where sensor_id = " + idAlicate + " && id > " + numeroLinhas);
                while (rst.next()) {
                    StringBuilder stbHora = new StringBuilder(rst.getString("Hora"));
                    StringBuilder stbData = new StringBuilder(rst.getString("Data"));
                    int minTemp, horaTemp, diaTemp, mesTemp, anoTemp;
                    int indexDoisPontos = stbHora.indexOf(":");
                    horaTemp = Integer.parseInt(stbHora.substring(0, indexDoisPontos));
                    minTemp = Integer.parseInt(stbHora.substring(indexDoisPontos + 1, stbHora.length()));
                    int indexBarra = stbData.indexOf("/");
                    int indexSegundaBarra = stbData.indexOf("/", indexBarra + 1);
                    diaTemp = Integer.parseInt(stbData.substring(0, indexBarra));
                    mesTemp = Integer.parseInt(stbData.substring(indexBarra + 1, indexSegundaBarra));
                    anoTemp = Integer.parseInt(stbData.substring(indexSegundaBarra + 1, stbData.length()));
                    calendar.set(anoTemp, mesTemp - 1, diaTemp, horaTemp, minTemp);
                }
                if (mes && !dia && !hora && !minuto && corrente && !potencia && !moeda) {
                    while (demo.getTimeSeriesSendoUsado()) {
                        try {
                            Thread.sleep(5000);
                            System.out.println("== Aguardando timeSeriesSerUsado ThreadAtulizaSerie==");
                        } catch (InterruptedException ex) {
                            Logger.getLogger(ProgramaGraficos.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                    demo.setTimeSeriesSendoUsado(true);
                    System.out.println("=== Atualizando serie meses do ano ===");
                    ResultSet rst2 = conexao.selectFromWhere("select valor from leituras where sensor_id = " + idAlicate + " && Data like '%/" + (calendar.get(Calendar.MONTH) + 1) + "/" + (calendar.get(Calendar.YEAR)) + "'");
                    System.out.println("select valor from leituras where sensor_id = " + idAlicate + " && Data like '%/" + (calendar.get(Calendar.MONTH) + 1) + "/" + (calendar.get(Calendar.YEAR)) + "'");
                    double aux = 0.0;
                    int numeroLinhasTemp2 = 0;
                    boolean valorMaiorMudou = false;
                    while (rst2.next()) {
                        aux += rst2.getDouble("valor");
                        numeroLinhasTemp2++;
                    }
                    if (aux != 0) {
                        if (aux / numeroLinhasTemp2 > maiorValorMes) {
                            maiorValorMes = aux / numeroLinhasTemp2;
                            valorMaiorMudou = true;
                        }
                        seriesMes.addOrUpdate(new Month((calendar.get(Calendar.MONTH) + 1), calendar.get(Calendar.YEAR) + 2000), aux / numeroLinhasTemp2);
                        System.out.println("== Atualizando serie ==");
                    }
                    if (valorMaiorMudou) {
                        plot.getRangeAxis().setRange(0, maiorValorMes + 2);
                    }
                    demo.setTimeSeriesSendoUsado(false);
                } else if (dia && !mes && !hora && !minuto && (demo.getCalendar().get(Calendar.MONTH)) == mesClicado && corrente && !potencia && !moeda) {
                    while (demo.getTimeSeriesSendoUsado()) {
                        try {
                            Thread.sleep(5000);
                            System.out.println("== Aguardando timeSeriesSerUsado ThreadAtulizaSerie==");
                        } catch (InterruptedException ex) {
                            Logger.getLogger(ProgramaGraficos.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                    demo.setTimeSeriesSendoUsado(true);
                    System.out.println("=== Atualizando serie dias do mes ===");
                    double aux = 0.0;
                    ResultSet rst2 = conexao.selectFromWhere("select valor from leituras where sensor_id = " + idAlicate + " && Data = '" + calendar.get(Calendar.DAY_OF_MONTH) + "/" + (calendar.get(Calendar.MONTH) + 1) + "/" + (calendar.get(Calendar.YEAR)) + "'");
                    System.out.println("select valor from leituras where sensor_id = " + idAlicate + " && Data = '" + calendar.get(Calendar.DAY_OF_MONTH) + "/" + (calendar.get(Calendar.MONTH) + 1) + "/" + (calendar.get(Calendar.YEAR)) + "'");
                    int numeroLinhasTemp2 = 0;
                    while (rst2.next()) {
                        aux += rst2.getDouble("valor");
                        numeroLinhasTemp2++;
                    }
                    if (aux != 0) {
                        serieDia.addOrUpdate(new Day(calendar.get(Calendar.DAY_OF_MONTH), (calendar.get(Calendar.MONTH) + 1), (calendar.get(Calendar.YEAR) + 2000)), aux / numeroLinhasTemp2);
                        System.out.println("=== Atualizando serie ===");
                    }
                    demo.setTimeSeriesSendoUsado(false);
                } else if (hora && !mes && !dia && !minuto && demo.getCalendar().get(Calendar.DAY_OF_MONTH) == diaClicado && corrente && !potencia && !moeda) {
                    while (demo.getTimeSeriesSendoUsado()) {
                        try {
                            Thread.sleep(5000);
                            System.out.println("== Aguardando timeSeriesSerUsado ThreadAtulizaSerie==");
                        } catch (InterruptedException ex) {
                            Logger.getLogger(ProgramaGraficos.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                    demo.setTimeSeriesSendoUsado(true);
                    System.out.println("=== Atualizando serie horas do mes ===");
                    ResultSet rst2 = conexao.selectFromWhere("select Hora, valor from leituras where sensor_id = " + idAlicate + " && Data = '" + calendar.get(Calendar.DAY_OF_MONTH) + "/" + (calendar.get(Calendar.MONTH) + 1) + "/" + calendar.get(Calendar.YEAR) + "' && Hora like '" + (calendar.get(Calendar.HOUR_OF_DAY)) + ":%'");
                    System.out.println("select Hora, valor from leituras where sensor_id = " + idAlicate + " && Data = '" + calendar.get(Calendar.DAY_OF_MONTH) + "/" + (calendar.get(Calendar.MONTH) + 1) + "/" + calendar.get(Calendar.YEAR) + "' && Hora like '" + (calendar.get(Calendar.HOUR_OF_DAY)) + ":%'");
                    double aux = 0.0;
                    boolean maiorValorMudou = false;
                    while (rst2.next()) {
                        aux += rst2.getDouble("valor");
                        StringBuilder stbHora = new StringBuilder(rst2.getString("Hora"));
                        int minTemp;
                        int indexDoisPontos = stbHora.indexOf(":");
                        minTemp = Integer.parseInt(stbHora.substring(indexDoisPontos + 1, stbHora.length()));
                        serieHora.addOrUpdate(new Minute(minTemp, calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.DAY_OF_MONTH), (calendar.get(Calendar.MONTH) + 1), calendar.get(Calendar.YEAR) + 2000), aux);
                        if (aux > maiorValorHora) {
                            maiorValorHora = aux;
                            maiorValorMudou = true;
                        }
                        aux = 0.0;
                        System.out.println("=== Atualizando serie ===");
                    }
                    if (maiorValorMudou) {
                        plot.getRangeAxis().setRange(0,maiorValorHora + 2);
                    }
                    demo.setTimeSeriesSendoUsado(false);
                } else if (minuto && !mes && !dia && !hora && demo.getCalendar().get(Calendar.HOUR_OF_DAY) == horaClicada && corrente && !potencia && !moeda) {
                    while (demo.getTimeSeriesSendoUsado()) {
                        try {
                            Thread.sleep(5000);
                            System.out.println("== Aguardando timeSeriesSerUsado ThreadAtulizaSerie==");
                        } catch (InterruptedException ex) {
                            Logger.getLogger(ProgramaGraficos.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                    demo.setTimeSeriesSendoUsado(true);
                    System.out.println("=== Atualizando serie minutos da hora ===");
                    rst = conexao.selectFromWhere("select Data, Hora, valor from leituras where sensor_id = " + idAlicate + " && Data = '" + calendar.get(Calendar.DAY_OF_MONTH) + "/" + (calendar.get(Calendar.MONTH) + 1) + "/" + calendar.get(Calendar.YEAR) + "' && Hora like '" + (calendar.get(Calendar.HOUR_OF_DAY)) + ":%'");
                    System.out.println("select Data, Hora, valor from leituras where sensor_id = " + idAlicate + " && Data = '" + calendar.get(Calendar.DAY_OF_MONTH) + "/" + (calendar.get(Calendar.MONTH) + 1) + "/" + calendar.get(Calendar.YEAR) + "' && Hora like '" + (calendar.get(Calendar.HOUR_OF_DAY)) + ":%'");
                    boolean maiorVlaorMinMudou = false;
                    while (rst.next()) {
                        StringBuilder stbHora = new StringBuilder(rst.getString("Hora"));
                        StringBuilder stbData = new StringBuilder(rst.getString("Data"));
                        int minTemp, horaTemp, diaTemp, mesTemp, anoTemp;
                        int indexDoisPontos = stbHora.indexOf(":");
                        horaTemp = Integer.parseInt(stbHora.substring(0, indexDoisPontos));
                        minTemp = Integer.parseInt(stbHora.substring(indexDoisPontos + 1, stbHora.length()));
                        int indexBarra = stbData.indexOf("/");
                        int indexSegundaBarra = stbData.indexOf("/", indexBarra + 1);
                        diaTemp = Integer.parseInt(stbData.substring(0, indexBarra));
                        mesTemp = Integer.parseInt(stbData.substring(indexBarra + 1, indexSegundaBarra));
                        anoTemp = Integer.parseInt(stbData.substring(indexSegundaBarra + 1, stbData.length()));
                        demo.getTimeSeriesCollection().getSeries("minuto").addOrUpdate(new Minute(minTemp, horaTemp, diaTemp, mesTemp, anoTemp + 2000), rst.getDouble("valor"));
                        if (rst.getDouble("valor") > maiorValorMinuto) {
                            maiorValorMinuto = rst.getDouble("valor");
                            maiorVlaorMinMudou = true;
                        }
                        System.out.println("=== Atualizando serie ===");
                    }
                    if (maiorVlaorMinMudou) {
                        plot.getRangeAxis().setRange(0,maiorValorMinuto + 2);
                    }
                    demo.setTimeSeriesSendoUsado(false);
                } else if (mes && !dia && !hora && !minuto && !corrente && potencia && !moeda) {
                    while (demo.getTimeSeriesSendoUsado()) {
                        try {
                            Thread.sleep(5000);
                            System.out.println("== Aguardando timeSeriesSerUsado ThreadAtulizaSerie==");
                        } catch (InterruptedException ex) {
                            Logger.getLogger(ProgramaGraficos.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                    demo.setTimeSeriesSendoUsado(true);
                    double aux = 0.0;
                    int numeroLinhas2 = 0;
                    boolean maiorValorEncontrado = false;
                    try {
                        rst = conexao.selectFromWhere("select valor from leituras where sensor_id = " + idAlicate + " && Data like '%/" + (calendar.get(Calendar.MONTH) + 1) + "/" + (calendar.get(Calendar.YEAR)) + "'");
                        System.out.println("select valor from leituras where sensor_id = " + idAlicate + " && Data like '%/" + (calendar.get(Calendar.MONTH) + 1) + "/" + (calendar.get(Calendar.YEAR)) + "'");
                        while (rst.next()) {
                            aux += rst.getDouble("valor");
                            numeroLinhas2++;
                        }
                        System.out.println("=== Atualizando serie ===");
                        seriesMes.update(new Month((calendar.get(Calendar.MONTH) + 1), anoAtual + 2000), (aux * 127) / 1000);
                        if ((aux * 127) / 1000 > maiorValorMes) {
                            maiorValorMes = (aux * 127) / 1000;
                            maiorValorEncontrado = true;
                        }
                    } catch (SQLException ex) {
                    }
                    if (maiorValorEncontrado) {
                        plot.getRangeAxis().setRange(0,maiorValorMes + 5);
                    }
                    demo.setTimeSeriesSendoUsado(false);
                } else if (dia && !mes && !hora && !minuto && (demo.getCalendar().get(Calendar.MONTH)) == mesClicado && !corrente && potencia && !moeda) {
                    while (demo.getTimeSeriesSendoUsado()) {
                        try {
                            Thread.sleep(5000);
                            System.out.println("== Aguardando timeSeriesSerUsado ThreadAtulizaSerie==");
                        } catch (InterruptedException ex) {
                            Logger.getLogger(ProgramaGraficos.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                    demo.setTimeSeriesSendoUsado(true);
                    double aux = 0.0;
                    boolean maiorValorMudou = false;
                    ResultSet rst2 = conexao.selectFromWhere("select valor from leituras where sensor_id = " + idAlicate + " && Data = '" + calendar.get(Calendar.DAY_OF_MONTH) + "/" + (calendar.get(Calendar.MONTH) + 1) + "/" + (calendar.get(Calendar.YEAR)) + "'");
                    System.out.println("select valor from leituras where sensor_id = " + idAlicate + " && Data = '" + calendar.get(Calendar.DAY_OF_MONTH) + "/" + (calendar.get(Calendar.MONTH) + 1) + "/" + (calendar.get(Calendar.YEAR)) + "'");
                    int numeroLinhasTemp2 = 0;
                    while (rst2.next()) {
                        aux += rst2.getDouble("valor");
                        numeroLinhasTemp2++;
                    }
                    serieDia.addOrUpdate(new Day(calendar.get(Calendar.DAY_OF_MONTH), (calendar.get(Calendar.MONTH) + 1), anoAtual + 2000), (aux * 127) / 1000);
                    if ((aux * 127) / 1000 > maiorValorDia) {
                        maiorValorDia = (aux * 127) / 1000;
                        maiorValorMudou = true;
                    }
                    if (maiorValorMudou) {
                        plot.getRangeAxis().setRange(0,maiorValorDia + 5);
                    }
                    demo.setTimeSeriesSendoUsado(false);
                } else if (hora && !mes && !dia && !minuto && demo.getCalendar().get(Calendar.DAY_OF_MONTH) == diaClicado && !corrente && potencia && !moeda) {
                    while (demo.getTimeSeriesSendoUsado()) {
                        try {
                            Thread.sleep(5000);
                            System.out.println("== Aguardando timeSeriesSerUsado ThreadAtulizaSerie==");
                        } catch (InterruptedException ex) {
                            Logger.getLogger(ProgramaGraficos.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                    demo.setTimeSeriesSendoUsado(true);
                    double aux = 0.0;
                    boolean maiorValorMudou = false;
                    ResultSet rst2 = conexao.selectFromWhere("select Hora, valor from leituras where sensor_id = " + idAlicate + " && Data = '" + calendar.get(Calendar.DAY_OF_MONTH) + "/" + (calendar.get(Calendar.MONTH) + 1) + "/" + calendar.get(Calendar.YEAR) + "' && Hora like '" + (calendar.get(Calendar.HOUR_OF_DAY)) + ":%'");
                    System.out.println("select Hora, valor from leituras where sensor_id = " + idAlicate + " && Data = '" + calendar.get(Calendar.DAY_OF_MONTH) + "/" + (calendar.get(Calendar.MONTH) + 1) + "/" + calendar.get(Calendar.YEAR) + "' && Hora like '" + (calendar.get(Calendar.HOUR_OF_DAY)) + ":%'");
                    while (rst2.next()) {
                        aux += rst2.getDouble("valor");
                    }
                    if (((aux) * 127) / 1000 > maiorValorHora) {
                        maiorValorHora = ((aux) * 127) / 1000;
                        maiorValorMudou = true;
                    }
                    serieHora.addOrUpdate(new Hour(calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.DATE), (calendar.get(Calendar.MONTH) + 1), anoAtual + 2000), ((aux) * 127) / 1000);
                    if(maiorValorMudou) {
                        plot.getRangeAxis().setRange(0,maiorValorHora + 5);
                    }
                    demo.setTimeSeriesSendoUsado(false);
                } else if (mes && !dia && !hora && !minuto && !corrente && !potencia && moeda) {
                    while (demo.getTimeSeriesSendoUsado()) {
                        try {
                            Thread.sleep(5000);
                            System.out.println("== Aguardando timeSeriesSerUsado ThreadAtulizaSerie==");
                        } catch (InterruptedException ex) {
                            Logger.getLogger(ProgramaGraficos.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                    demo.setTimeSeriesSendoUsado(true);
                    boolean maiorValorMudou = false;
                    int numeroLinhas2 = 0;
                    double aux = 0.0;
                    try {
                        rst = conexao.selectFromWhere("select valor from leituras where sensor_id = " + idAlicate + " && Data like '%/" + (calendar.get(Calendar.MONTH) + 1) + "/" + (calendar.get(Calendar.YEAR)) + "'");
                        System.out.println("select valor from leituras where sensor_id = " + idAlicate + " && Data like '%/" + (calendar.get(Calendar.MONTH) + 1) + "/" + (calendar.get(Calendar.YEAR)) + "'");
                        while (rst.next()) {
                            aux += rst.getDouble("valor");
                            numeroLinhas2++;
                        }
                        System.out.println("=== Atualizando serie ===");
                        seriesMes.update(new Month((calendar.get(Calendar.MONTH) + 1), anoAtual + 2000), ((aux * 127) / 1000) * demo.getTarifa());
                        if (((aux * 127) / 1000) * demo.getTarifa() > maiorValorMes) {
                            maiorValorMes = ((aux * 127) / 1000) * demo.getTarifa();
                            maiorValorMudou = true;
                        }
                    } catch (SQLException ex) {
                    }
                    if (maiorValorMudou) {
                        plot.getRangeAxis().setRange(0,maiorValorMes + 2);
                    }
                    demo.setTimeSeriesSendoUsado(false);
                } else if (dia && !mes && !hora && !minuto && (demo.getCalendar().get(Calendar.MONTH)) == mesClicado && !corrente && !potencia && moeda) {
                    while (demo.getTimeSeriesSendoUsado()) {
                        try {
                            Thread.sleep(5000);
                            System.out.println("== Aguardando timeSeriesSerUsado ThreadAtulizaSerie==");
                        } catch (InterruptedException ex) {
                            Logger.getLogger(ProgramaGraficos.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                    demo.setTimeSeriesSendoUsado(true);
                    double aux = 0.0;
                    boolean maiorValorMudou = false;
                    ResultSet rst2 = conexao.selectFromWhere("select valor from leituras where sensor_id = " + idAlicate + " && Data = '" + calendar.get(Calendar.DAY_OF_MONTH) + "/" + (calendar.get(Calendar.MONTH) + 1) + "/" + (calendar.get(Calendar.YEAR)) + "'");
                    System.out.println("select valor from leituras where sensor_id = " + idAlicate + " && Data = '" + calendar.get(Calendar.DAY_OF_MONTH) + "/" + (calendar.get(Calendar.MONTH) + 1) + "/" + (calendar.get(Calendar.YEAR)) + "'");
                    int numeroLinhasTemp2 = 0;
                    while (rst2.next()) {
                        aux += rst2.getDouble("valor");
                        numeroLinhasTemp2++;
                    }
                    serieDia.addOrUpdate(new Day(calendar.get(Calendar.DAY_OF_MONTH), (calendar.get(Calendar.MONTH) + 1), anoAtual + 2000), ((aux * 127) / 1000) * tarifaLuz);
                    if (((aux * 127) / 1000) * tarifaLuz > maiorValorDia) {
                        maiorValorDia = ((aux * 127) / 1000) * tarifaLuz;
                        maiorValorMudou = true;
                    }
                    if (maiorValorMudou) {
                        plot.getRangeAxis().setRange(0,maiorValorDia + 2);
                    }
                    demo.setTimeSeriesSendoUsado(false);
                } else if (hora && !mes && !dia && !minuto && demo.getCalendar().get(Calendar.DAY_OF_MONTH) == diaClicado && !corrente && !potencia && moeda) {
                    while (demo.getTimeSeriesSendoUsado()) {
                        try {
                            Thread.sleep(5000);
                            System.out.println("== Aguardando timeSeriesSerUsado ThreadAtulizaSerie==");
                        } catch (InterruptedException ex) {
                            Logger.getLogger(ProgramaGraficos.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                    demo.setTimeSeriesSendoUsado(true);
                    double aux = 0.0;
                    boolean maiorValorMudou = false;
                    ResultSet rst2 = conexao.selectFromWhere("select Hora, valor from leituras where sensor_id = " + idAlicate + " && Data = '" + calendar.get(Calendar.DAY_OF_MONTH) + "/" + (calendar.get(Calendar.MONTH) + 1) + "/" + calendar.get(Calendar.YEAR) + "' && Hora like '" + (calendar.get(Calendar.HOUR_OF_DAY)) + ":%'");
                    System.out.println("select Hora, valor from leituras where sensor_id = " + idAlicate + " && Data = '" + calendar.get(Calendar.DAY_OF_MONTH) + "/" + (calendar.get(Calendar.MONTH) + 1) + "/" + calendar.get(Calendar.YEAR) + "' && Hora like '" + (calendar.get(Calendar.HOUR_OF_DAY)) + ":%'");
                    while (rst2.next()) {
                        aux += rst2.getDouble("valor");
                    }
                    if (((aux * 127) / 1000) * tarifaLuz > maiorValorHora) {
                        maiorValorHora = ((aux * 127) / 1000) * tarifaLuz;
                        maiorValorMudou = true;
                    }
                    serieHora.addOrUpdate(new Hour(calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.DATE), (calendar.get(Calendar.MONTH) + 1), anoAtual + 2000), ((aux * 127) / 1000) * tarifaLuz);
                    if(maiorValorMudou) {
                        plot.getRangeAxis().setRange(0,maiorValorHora + 2);
                    }   

                    demo.setTimeSeriesSendoUsado(false);
                } 
                rst = conexao.selectFromWhere("select id from leituras where sensor_id = " + idAlicate);
                rst.last();
                numeroLinhas = rst.getInt("id");
            }
        } catch (SQLException ex) {
        }
        System.out.println("passou 1 minuto");
    }

    public static void gerarTimeSeriesMes() {
        seriesMes.clear();
        maiorValorMes = 0;
        for (int i = 1; i <= 12; i++) {
            ResultSet rst;
            double aux = 0.0;
            try {
                rst = conexao.selectFromWhere("select valor from leituras where sensor_id = " + idAlicate + " && Data like '%/" + i + "/" + anoAtual + "'");
                int numeroLin = 0;
                while (rst.next()) {
                    aux += rst.getDouble("valor");
                    numeroLin++;
                }
                seriesMes.addOrUpdate(new Month(i, anoAtual + 2000), aux / numeroLin);
                if (aux / numeroLin > maiorValorMes) {
                    maiorValorMes = aux / numeroLin;
                }
            } catch (SQLException ex) {
            }
        }
        DateFormat formatter = new SimpleDateFormat("MMM");
        DateAxis axis = (DateAxis) plot.getDomainAxis();
        axis.setDateFormatOverride(formatter);
        DateTickUnit unit = new DateTickUnit(DateTickUnitType.MONTH, 1);
        TickUnits units = new TickUnits();
        units.add(unit);
        plot.getDomainAxis().setStandardTickUnits(units);
        plot.getDomainAxis().setLabel("Mês");
        plot.getRangeAxis().setLabel("Corrente (A)");
        plot.getDomainAxis().setRange(new Month(1, 2013).getFirstMillisecond(), new Month(12, 2013).getLastMillisecond());
        plot.getRangeAxis().setRange(0,maiorValorMes + 2);
        plot.setDataset((new TimeSeriesCollection(demo.getTimeSeriesCollection().getSeries("mes"))));
        demo.setTitle((anoAtual + 2000) + " sensor: " + alicateNome);
        demo.setVisible(true);
    }

    public static void gerarTimeSeriesMesesKw() {
        maiorValorMes = 0;
        for (int i = 1; i <= 12; i++) {
            ResultSet rst;
            double aux = 0.0;
            int numeroLinhas2 = 0;
            try {
                rst = conexao.selectFromWhere("select valor from leituras where sensor_id = " + idAlicate + " && Data like '%/" + i + "/" + anoAtual + "'");
                while (rst.next()) {
                    aux += rst.getDouble("valor");
                    numeroLinhas2++;
                }
                seriesMes.update(new Month(i, anoAtual + 2000), (aux * 127) / 1000);
                if ((aux * 127) / 1000 > maiorValorMes) {
                    maiorValorMes = (aux * 127) / 1000;
                }
            } catch (SQLException ex) {
            }
        }
        plot.getRangeAxis().setRange(0,maiorValorMes + 5);
        plot.getRangeAxis().setLabel("Potência (kWh)");
        demo.setVisible(true);
    }

    public static void gerarTimeSeriesMesesreais() {
        maiorValorMes = 0;
        for (int i = 0; i < seriesMes.getItemCount(); i++) {
            seriesMes.update(seriesMes.getTimePeriod(i), (double) (seriesMes.getValue(i)) * demo.getTarifa());
            if ((double) (seriesMes.getValue(i)) > maiorValorMes) {
                maiorValorMes = (double) (seriesMes.getValue(i));
            }
        }
        plot.getRangeAxis().setRange(0,maiorValorMes +2);
        plot.getRangeAxis().setLabel("Valores (R$)");
        demo.setVisible(true);
    }
    
    public static void gerarTimeSeresDias() throws SQLException {
        serieDia.clear();
        ResultSet rst;
        double aux = 0.0;
        int numLin = 0;
        maiorValorDia = 0;
        for (int i = 1; i <= calendar.getActualMaximum(Calendar.DAY_OF_MONTH); i++) {
            rst = conexao.selectFromWhere("select valor from leituras where sensor_id = " + idAlicate + " && Data like '" + i + "/" + (calendar.get(Calendar.MONTH) + 1) + "/" + anoAtual + "'");
            while (rst.next()) {
                aux += rst.getDouble("valor");
                numLin++;
            }
            serieDia.addOrUpdate(new Day(i, (calendar.get(Calendar.MONTH) + 1), anoAtual + 2000), aux / numLin);
            if (aux / numLin > maiorValorDia) {
                maiorValorDia = aux / numLin;
            }
            aux = 0.0;
            numLin = 0;
        }
        demo.setTitle("" + new Month(calendar.getTime()) + " sensor: " + alicateNome);
        DateTickUnit unit = new DateTickUnit(DateTickUnitType.DAY, 2);
        TickUnits units = new TickUnits();
        units.add(unit);
        plot.getDomainAxis().setStandardTickUnits(units);
        DateFormat formatter = new SimpleDateFormat("dd");
        DateAxis axis = (DateAxis) plot.getDomainAxis();
        axis.setDateFormatOverride(formatter);
        plot.getDomainAxis().setLabel("Dia");
        plot.getRangeAxis().setLabel("Corrente (A)");
        xYBarRenderer.setLegendItemLabelGenerator(new StandardXYSeriesLabelGenerator("{0}"));
        plot.getDomainAxis().setRange(new Day(1, (calendar.get(Calendar.MONTH) + 1), anoAtual + 2000).getFirstMillisecond(), new Day(calendar.getActualMaximum(Calendar.DAY_OF_MONTH), (calendar.get(Calendar.MONTH) + 1), anoAtual + 2000).getLastMillisecond());
        plot.getRangeAxis().setRange(0,maiorValorDia + 2);
        plot.setDataset((new TimeSeriesCollection(demo.getTimeSeriesCollection().getSeries("dia"))));
        plot.setRenderer(xYBarRenderer);
        demo.setVisible(true);
    }

    private void gerarTimeSeriesDiaKw() throws SQLException {
        serieDia.clear();
        maiorValorDia = 0;
        ResultSet rst;
        double aux = 0.0;
        for (int i = 1; i <= calendar.getActualMaximum(Calendar.DAY_OF_MONTH); i++) {
            rst = conexao.selectFromWhere("select valor from leituras where sensor_id = " + idAlicate + " && Data like '" + i + "/" + (calendar.get(Calendar.MONTH) + 1) + "/" + anoAtual + "'");
            while (rst.next()) {
                aux += rst.getDouble("valor");
            }
            serieDia.addOrUpdate(new Day(i, (calendar.get(Calendar.MONTH) + 1), anoAtual + 2000), (aux * 127) / 1000);
            if ((aux * 127) / 1000 > maiorValorDia) {
                maiorValorDia = (aux * 127) / 1000;
            }
            aux = 0.0;
        }
        plot.getRangeAxis().setLabel("Potência (kWh)");
        plot.getRangeAxis().setRange(0,maiorValorDia + 5);
        demo.setVisible(true);
    }

    private void gerarTimeSeriesDiareais() throws SQLException {
        serieDia.clear();
        ResultSet rst;
        maiorValorDia = 0;
        double aux = 0.0;
        for (int i = 1; i <= calendar.getActualMaximum(Calendar.DAY_OF_MONTH); i++) {
            rst = conexao.selectFromWhere("select valor from leituras where sensor_id = " + idAlicate + " && Data like '" + i + "/" + (calendar.get(Calendar.MONTH) + 1) + "/" + anoAtual + "'");
            while (rst.next()) {
                aux += rst.getDouble("valor");
            }
            serieDia.addOrUpdate(new Day(i, (calendar.get(Calendar.MONTH) + 1), anoAtual + 2000), ((aux * 127) / 1000) * tarifaLuz);
            if (((aux * 127) / 1000) * tarifaLuz > maiorValorDia) {
                maiorValorDia = ((aux * 127) / 1000) * tarifaLuz;
            }
            aux = 0.0;
        }
        plot.getRangeAxis().setLabel("Valores (R$)");
        plot.getRangeAxis().setRange(0,maiorValorDia + 2);
        demo.setVisible(true);
    }

    public static void gerarTimeSeriesHoras() {
        serieHora.clear();
        maiorValorHora = 0.0;
        try {
            for (int i = 0; i < 24; i++) {
                ResultSet rst = conexao.selectFromWhere("select Hora, valor from leituras where sensor_id = " + idAlicate + " && Data = '" + calendar.get(Calendar.DATE) + "/" + (calendar.get(Calendar.MONTH) + 1) + "/" + anoAtual + "' && Hora like '" + i + ":%'");
                double aux = 0.0;
                while (rst.next()) {
                    StringBuilder stbHora = new StringBuilder(rst.getString("Hora"));
                    int minTemp;
                    int indexDoisPontos = stbHora.indexOf(":");
                    minTemp = Integer.parseInt(stbHora.substring(indexDoisPontos + 1, stbHora.length()));
                    aux += rst.getDouble("valor");
                    serieHora.addOrUpdate(new Minute(minTemp, i, calendar.get(Calendar.DATE), (calendar.get(Calendar.MONTH) + 1), anoAtual + 2000), aux); /// numeroLinhas);
                    if (aux > maiorValorHora) {
                        maiorValorHora = aux;
                    }
                    aux = 0.0;
                }
            }
            demo.setTitle("" + new Day(calendar.getTime()) + " sensor: " + alicateNome);
            DateTickUnit unit = new DateTickUnit(DateTickUnitType.HOUR, 1);
            TickUnits units = new TickUnits();
            units.add(unit);
            plot.getDomainAxis().setStandardTickUnits(units);
            DateFormat formatter = new SimpleDateFormat("HH");
            DateAxis axis = (DateAxis) plot.getDomainAxis();
            axis.setDateFormatOverride(formatter);
            plot.getDomainAxis().setLabel("Hora");
            XYLineAndShapeRenderer xylineandshaperenderer4 = new XYLineAndShapeRenderer();
            java.awt.geom.Ellipse2D.Double double1 = new java.awt.geom.Ellipse2D.Double(-1D, -1D, 2D, 2D);
            xylineandshaperenderer4.setBaseSeriesVisibleInLegend(true);
            xylineandshaperenderer4.setSeriesShape(0, double1);
            xylineandshaperenderer4.setSeriesPaint(0, Color.red);
            xylineandshaperenderer4.setSeriesFillPaint(0, Color.black);
            xylineandshaperenderer4.setSeriesOutlinePaint(0, Color.black);
            xylineandshaperenderer4.setUseOutlinePaint(true);
            xylineandshaperenderer4.setUseFillPaint(true);
            xylineandshaperenderer4.setDrawOutlines(false);
            xylineandshaperenderer4.setSeriesToolTipGenerator(0, new XYToolTipGenerator() {

                @Override
                public String generateToolTip(XYDataset xyd, int i, int i1) {
                    DecimalFormat df = new DecimalFormat("0.00");
                    return "" + df.format((xyd.getYValue(i, i1)));
                }
            });
            plot.setRenderer(xylineandshaperenderer4);
            plot.getRangeAxis().setLabel("Corrente (A)");
            plot.getDomainAxis().setRange(new Hour(0, calendar.get(Calendar.DAY_OF_MONTH), (calendar.get(Calendar.MONTH) + 1), anoAtual + 2000).getFirstMillisecond(), new Hour(23, calendar.get(Calendar.DAY_OF_MONTH), (calendar.get(Calendar.MONTH) + 1), anoAtual + 2000).getLastMillisecond());
            plot.setDataset((new TimeSeriesCollection(demo.getTimeSeriesCollection().getSeries("hora"))));
            plot.setRenderer(xylineandshaperenderer4);
            axis.setTickMarkPosition(DateTickMarkPosition.START);
            plot.getRangeAxis().setRange(0,maiorValorHora + 2);
            demo.setVisible(true);
        } catch (SQLException ex) {
            Logger.getLogger(ProgramaGraficos.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void gerarTimeSeriesHoraKw() throws SQLException {
        serieHora.clear();
        maiorValorHora = 0.0;
        for (int i = 0; i < 24; i++) {
            ResultSet rst = conexao.selectFromWhere("select Hora, valor from leituras where sensor_id = " + idAlicate + " && Data = '" + calendar.get(Calendar.DATE) + "/" + (calendar.get(Calendar.MONTH) + 1) + "/" + anoAtual + "' && Hora like '" + i + ":%'");
            double aux = 0.0;
            while (rst.next()) {
                aux += rst.getDouble("valor");
            }
            if (((aux) * 127) / 1000 > maiorValorHora) {
                maiorValorHora = ((aux) * 127) / 1000;
            }
            serieHora.addOrUpdate(new Hour(i, calendar.get(Calendar.DATE), (calendar.get(Calendar.MONTH) + 1), anoAtual + 2000), ((aux) * 127) / 1000);
        }
        plot.getRangeAxis().setRange(0,maiorValorHora + 5);
        plot.getRangeAxis().setLabel("Potência (kWh)");
        plot.setRenderer(xYBarRenderer);
        demo.setVisible(true);
    }

    public void gerarTimeSeriesHoraReais() throws SQLException {
        for (int i = 0; i < 24; i++) {
            ResultSet rst = conexao.selectFromWhere("select Hora, valor from leituras where sensor_id = " + idAlicate + " && Data = '" + calendar.get(Calendar.DATE) + "/" + (calendar.get(Calendar.MONTH) + 1) + "/" + anoAtual + "' && Hora like '" + i + ":%'");
            double aux = 0.0;
            while (rst.next()) {
                aux += rst.getDouble("valor");
            }
            if (((aux * 127) / 1000) * tarifaLuz > maiorValorHora) {
                maiorValorHora = ((aux * 127) / 1000) * tarifaLuz;
            }
            serieHora.addOrUpdate(new Hour(i, calendar.get(Calendar.DATE), (calendar.get(Calendar.MONTH) + 1), anoAtual + 2000), ((aux * 127) / 1000) * tarifaLuz);
        }
        plot.getRangeAxis().setLabel("Valores (R$)");
        plot.getRangeAxis().setRange(0,maiorValorHora + 2);
        plot.setRenderer(xYBarRenderer);
        demo.setVisible(true);
    }

    public static void geraraTimeSeriesMinutos() {
        try {
            ResultSet rst = conexao.selectFromWhere("select Data, Hora, valor from leituras where sensor_id = " + idAlicate + " && Data = '" + calendar.get(Calendar.DATE) + "/" + (calendar.get(Calendar.MONTH) + 1) + "/" + anoAtual + "' && Hora like '" + calendar.get(Calendar.HOUR_OF_DAY) + ":%'");
            serieMinuto.clear();
            maiorValorMinuto = 0.0;
            while (rst.next()) {
                StringBuilder stbHora = new StringBuilder(rst.getString("Hora"));
                StringBuilder stbData = new StringBuilder(rst.getString("Data"));
                int minTemp, horaTemp, diaTemp, mesTemp, anoTemp;
                int indexDoisPontos = stbHora.indexOf(":");
                horaTemp = Integer.parseInt(stbHora.substring(0, indexDoisPontos));
                minTemp = Integer.parseInt(stbHora.substring(indexDoisPontos + 1, stbHora.length()));
                int indexBarra = stbData.indexOf("/");
                int indexSegundaBarra = stbData.indexOf("/", indexBarra + 1);
                diaTemp = Integer.parseInt(stbData.substring(0, indexBarra));
                mesTemp = Integer.parseInt(stbData.substring(indexBarra + 1, indexSegundaBarra));
                anoTemp = Integer.parseInt(stbData.substring(indexSegundaBarra + 1, stbData.length()));
                serieMinuto.addOrUpdate(new Minute(minTemp, horaTemp, diaTemp, mesTemp, anoTemp + 2000), rst.getDouble("valor"));
                if (rst.getDouble("valor") > maiorValorMinuto) {
                    maiorValorMinuto = rst.getDouble("valor");
                }
            }
            demo.setTitle("" + new Minute(calendar.getTime()) + " sensor: " + alicateNome);
            DateTickUnit unit = new DateTickUnit(DateTickUnitType.MINUTE, 5);
            TickUnits units = new TickUnits();
            units.add(unit);
            plot.getDomainAxis().setStandardTickUnits(units);
            DateFormat formatter = new SimpleDateFormat("mm");
            DateAxis axis = (DateAxis) plot.getDomainAxis();
            axis.setDateFormatOverride(formatter);
            XYLineAndShapeRenderer xylineandshaperenderer4 = new XYLineAndShapeRenderer();
            java.awt.geom.Ellipse2D.Double double1 = new java.awt.geom.Ellipse2D.Double(-1D, -1D, 2D, 2D);
            xylineandshaperenderer4.setBaseSeriesVisibleInLegend(true);
            xylineandshaperenderer4.setSeriesShape(0, double1);
            xylineandshaperenderer4.setSeriesPaint(0, Color.red);
            xylineandshaperenderer4.setSeriesFillPaint(0, Color.black);
            xylineandshaperenderer4.setSeriesOutlinePaint(0, Color.black);
            xylineandshaperenderer4.setUseOutlinePaint(true);
            xylineandshaperenderer4.setUseFillPaint(true);
            xylineandshaperenderer4.setDrawOutlines(false);
            plot.getDomainAxis().setLabel("Minuto");
            xylineandshaperenderer4.setSeriesToolTipGenerator(0, new XYToolTipGenerator() {

                @Override
                public String generateToolTip(XYDataset xyd, int i, int i1) {
                    DecimalFormat df = new DecimalFormat("0.00");
                    return "" + df.format((xyd.getYValue(i, i1)));
                }
            });
            DateAxis dateaxis = (DateAxis) plot.getDomainAxis();
            dateaxis.setTickMarkPosition(DateTickMarkPosition.START);
            plot.setRenderer(xylineandshaperenderer4);
            plot.getDomainAxis().setRange(new Minute(0, calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.DAY_OF_MONTH), (calendar.get(Calendar.MONTH) + 1), anoAtual + 2000).getFirstMillisecond(), new Minute(59, calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.DAY_OF_MONTH), (calendar.get(Calendar.MONTH) + 1), anoAtual + 2000).getLastMillisecond());
            plot.setDataset((new TimeSeriesCollection(demo.getTimeSeriesCollection().getSeries("minuto"))));
            plot.getRangeAxis().setRange(0,maiorValorMinuto +2);
            demo.setVisible(true);
        } catch (SQLException ex) {
            Logger.getLogger(ProgramaGraficos.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public static void main(String[] args) throws InterruptedException, Exception {
        calendar = Calendar.getInstance();
        timeseriescolletion = new TimeSeriesCollection();
        TelaSelectBD telaSelectBD = new TelaSelectBD();
        telaSelectBD.setVisible(true);
        while (telaSelectBD.getBotaoApertado() == false) {
            Thread.sleep(200);
        }
        telaSelectBD.setVisible(false);
        String bancodedados = telaSelectBD.getJTextFieldEnderecoBD().getText() + ":" + telaSelectBD.getJTextFieldPortaBD().getText() + "/" + telaSelectBD.getJTextFieldSchema().getText();
        conexao = new Conexao(bancodedados, telaSelectBD.getJTextFieldUsuarioBD().getText(), new String(telaSelectBD.getJTextFieldSenhaBD().getPassword()));
        TelaEscolhaGerente telaEscolhaGerente = new TelaEscolhaGerente();
        ResultSet rst = conexao.selectFromWhere("SELECT mac FROM gerentes");
        while (rst.next()) {
            telaEscolhaGerente.getjComboBox().addItem(rst.getInt("mac"));
        }
        telaEscolhaGerente.setVisible(true);
        while (telaEscolhaGerente.getBotaoApertado() == false) {
            Thread.sleep(200);
        }
        telaEscolhaGerente.setVisible(false);
        rst = conexao.selectFromWhere("select id from sensores where gerente_id = ( select id from gerentes where mac = " + telaEscolhaGerente.getjComboBox().getSelectedItem() + ")");
        rst.first();
        idAlicate = rst.getInt("id");
        rst = conexao.selectFromWhere("select nome from sensores where gerente_id = ( select id from gerentes where mac = " + telaEscolhaGerente.getjComboBox().getSelectedItem() + ")");
        TelaSelectAlicate telaSelectAlicate = new TelaSelectAlicate();
        while (rst.next()) {
            telaSelectAlicate.getjComboBox().addItem(rst.getString("nome"));
        }
        telaSelectAlicate.setVisible(true);
        while (telaSelectAlicate.getBotaoApertado() == false) {
            Thread.sleep(200);
        }
        telaSelectAlicate.setVisible(false);
        alicateNome = telaSelectAlicate.getjComboBox().getSelectedItem().toString();
        anoAtual = Calendar.getInstance().get(Calendar.YEAR) - 2000;
        seriesMes = new TimeSeries("mes");
        serieDia = new TimeSeries("dia");
        serieHora = new TimeSeries("hora");
        serieHora.setMaximumItemCount(1440);
        serieMinuto = new TimeSeries("minuto");
        createDataset();
        demo = new ProgramaGraficos(alicateNome, seriesMes);
        gerarTimeSeriesMes();
        demo.setTitle(alicateNome);
        DateFormat formatter = new SimpleDateFormat("MMM");
        DateAxis axis = (DateAxis) plot.getDomainAxis();
        axis.setDateFormatOverride(formatter);
        demo.pack();
        RefineryUtilities.centerFrameOnScreen(demo);
        demo.setDefaultCloseOperation(EXIT_ON_CLOSE);
        demo.setVisible(true);
    }

    @Override
    public void chartMouseClicked(ChartMouseEvent cme) {
        if (primeiroClick) {
            primeiroClick = !primeiroClick;
        } else {
            if (!dataVelha) {
                System.out.println("== Evento mouseListener ==");
                corrente = true;
                potencia = false;
                moeda = false;
                while (timeSeriesSendoUsado) {
                    try {
                        Thread.sleep(5000);
                        System.out.println("== Aguardando timeSeriesSerUsado mouseEvent==");


                    } catch (InterruptedException ex) {
                        Logger.getLogger(ProgramaGraficos.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
                timeSeriesSendoUsado = true;
                Date d = new Date((long) (cme.getChart().getXYPlot().getDomainCrosshairValue()));
                calendar.setTime(d);
                mesClicado = calendar.get(Calendar.MONTH);
                diaClicado = calendar.get(Calendar.DAY_OF_MONTH);
                horaClicada = calendar.get(Calendar.HOUR_OF_DAY);
                if (mes && !dia && !hora && !minuto) {
                    demo.setVisible(false);
                    try {
                        gerarTimeSeresDias();
                    } catch (SQLException ex) {
                        Logger.getLogger(ProgramaGraficos.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    mes = false;
                    dia = true;
                    hora = false;
                    minuto = false;
                } else if (dia && !mes && !hora && !minuto) {
                    demo.setVisible(false);
                    gerarTimeSeriesHoras();
                    hora = true;
                    dia = false;
                    mes = false;
                    minuto = false;
                } else if (hora && !mes && !dia && !minuto) {
                    demo.setVisible(false);
                    geraraTimeSeriesMinutos();
                    minuto = true;
                    dia = false;
                    mes = false;
                    hora = false;
                }
                timeSeriesSendoUsado = false;
                dataVelha = !dataVelha;
            } else {
                dataVelha = !dataVelha;
            }
        }
    }

    public synchronized boolean getTimeSeriesSendoUsado() {
        return timeSeriesSendoUsado;
    }

    @Override
    public void chartMouseMoved(ChartMouseEvent cme) {
    }

    @Override
    public void keyTyped(KeyEvent e) {
    }

    @Override
    public void keyPressed(KeyEvent e) {
    }

    @Override
    public void keyReleased(KeyEvent e) {
        System.out.println("=== Event keyListener ===");
        switch (e.getKeyCode()) {
            case KeyEvent.VK_ENTER:
                chartPanel.restoreAutoBounds();
                System.out.println("=== Chart atualizado ===");
                break;
            case KeyEvent.VK_ESCAPE:
                if (dia && !mes && !hora && !minuto) {
                    demo.setVisible(false);
                    while (timeSeriesSendoUsado) {
                        try {
                            Thread.sleep(5000);
                            System.out.println("== Aguardando timeSeriesSerUsado keyEvent==");
                        } catch (InterruptedException ex) {
                            Logger.getLogger(ProgramaGraficos.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                    timeSeriesSendoUsado = true;
                    gerarTimeSeriesMes();
                    mes = true;
                    dia = false;
                    hora = false;
                    minuto = false;
                    timeSeriesSendoUsado = false;
                } else if (hora && !mes && !dia && !minuto) {
                    demo.setVisible(false);
                    while (timeSeriesSendoUsado) {
                        try {
                            Thread.sleep(5000);
                            System.out.println("== Aguardando timeSeriesSerUsado keyEvent==");
                        } catch (InterruptedException ex) {
                            Logger.getLogger(ProgramaGraficos.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                    timeSeriesSendoUsado = true;
                    try {
                        gerarTimeSeresDias();
                    } catch (SQLException ex) {
                        Logger.getLogger(ProgramaGraficos.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    mes = false;
                    dia = true;
                    hora = false;
                    minuto = false;
                    timeSeriesSendoUsado = false;
                } else if (minuto && !dia && !mes && !hora) {
                    demo.setVisible(false);
                    while (timeSeriesSendoUsado) {
                        try {
                            Thread.sleep(5000);
                            System.out.println("== Aguardando timeSeriesSerUsado keyEvent==");


                        } catch (InterruptedException ex) {
                            Logger.getLogger(ProgramaGraficos.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                    timeSeriesSendoUsado = true;
                    gerarTimeSeriesHoras();
                    mes = false;
                    dia = false;
                    hora = true;
                    minuto = false;
                    timeSeriesSendoUsado = false;
                }
                break;
            case KeyEvent.VK_RIGHT:
                if (corrente && !potencia && !moeda && mes && !dia && !hora && !minuto) {
                    demo.setVisible(false);
                    while (timeSeriesSendoUsado) {
                        try {
                            Thread.sleep(5000);
                            System.out.println("== Aguardando timeSeriesSerUsado keyEvent==");


                        } catch (InterruptedException ex) {
                            Logger.getLogger(ProgramaGraficos.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                    timeSeriesSendoUsado = true;
                    gerarTimeSeriesMesesKw();
                    timeSeriesSendoUsado = false;
                    corrente = false;
                    potencia = true;
                    moeda = false;
                } else if (!corrente && potencia && !moeda && mes && !dia && !hora && !minuto) {
                    demo.setVisible(false);
                    while (timeSeriesSendoUsado) {
                        try {
                            Thread.sleep(5000);
                            System.out.println("== Aguardando timeSeriesSerUsado keyEvent==");


                        } catch (InterruptedException ex) {
                            Logger.getLogger(ProgramaGraficos.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                    timeSeriesSendoUsado = true;
                    gerarTimeSeriesMesesreais();
                    timeSeriesSendoUsado = false;
                    corrente = false;
                    potencia = false;
                    moeda = true;
                } else if (corrente && !potencia && !moeda && !mes && dia && !hora && !minuto) {
                    demo.setVisible(false);
                    while (timeSeriesSendoUsado) {
                        try {
                            Thread.sleep(5000);
                            System.out.println("== Aguardando timeSeriesSerUsado keyEvent==");


                        } catch (InterruptedException ex) {
                            Logger.getLogger(ProgramaGraficos.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                    timeSeriesSendoUsado = true;
                    try {
                        gerarTimeSeriesDiaKw();
                    } catch (SQLException ex) {
                        Logger.getLogger(ProgramaGraficos.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    timeSeriesSendoUsado = false;
                    corrente = false;
                    potencia = true;
                    moeda = false;
                } else if (!corrente && potencia && !moeda && !mes && dia && !hora && !minuto) {
                    demo.setVisible(false);
                    while (timeSeriesSendoUsado) {
                        try {
                            Thread.sleep(5000);
                            System.out.println("== Aguardando timeSeriesSerUsado keyEvent==");


                        } catch (InterruptedException ex) {
                            Logger.getLogger(ProgramaGraficos.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                    timeSeriesSendoUsado = true;
                    try {
                        gerarTimeSeriesDiareais();
                    } catch (SQLException ex) {
                        Logger.getLogger(ProgramaGraficos.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    timeSeriesSendoUsado = false;
                    corrente = false;
                    potencia = false;
                    moeda = true;
                } else if (corrente && !potencia && !moeda && !mes && !dia && hora && !minuto) {
                    demo.setVisible(false);
                    while (timeSeriesSendoUsado) {
                        try {
                            Thread.sleep(5000);
                            System.out.println("== Aguardando timeSeriesSerUsado keyEvent==");


                        } catch (InterruptedException ex) {
                            Logger.getLogger(ProgramaGraficos.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                    timeSeriesSendoUsado = true;
                    try {
                        gerarTimeSeriesHoraKw();
                    } catch (SQLException ex) {
                        Logger.getLogger(ProgramaGraficos.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    timeSeriesSendoUsado = false;
                    corrente = false;
                    potencia = true;
                    moeda = false;
                } else if (!corrente && potencia && !moeda && !mes && !dia && hora && !minuto) {
                    demo.setVisible(false);
                    while (timeSeriesSendoUsado) {
                        try {
                            Thread.sleep(5000);
                            System.out.println("== Aguardando timeSeriesSerUsado keyEvent==");


                        } catch (InterruptedException ex) {
                            Logger.getLogger(ProgramaGraficos.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                    timeSeriesSendoUsado = true;
                    try {
                        gerarTimeSeriesHoraReais();
                    } catch (SQLException ex) {
                        Logger.getLogger(ProgramaGraficos.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    timeSeriesSendoUsado = false;
                    corrente = false;
                    potencia = false;
                    moeda = true;
                }
                break;
            case KeyEvent.VK_LEFT:
                if (!corrente && !potencia && moeda && mes && !dia && !hora && !minuto) {
                    demo.setVisible(false);
                    while (timeSeriesSendoUsado) {
                        try {
                            Thread.sleep(5000);
                            System.out.println("== Aguardando timeSeriesSerUsado keyEvent==");


                        } catch (InterruptedException ex) {
                            Logger.getLogger(ProgramaGraficos.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                    timeSeriesSendoUsado = true;
                    gerarTimeSeriesMesesKw();
                    timeSeriesSendoUsado = false;
                    corrente = false;
                    potencia = true;
                    moeda = false;
                } else if (!corrente && potencia && !moeda && mes && !dia && !hora && !minuto) {
                    demo.setVisible(false);
                    while (timeSeriesSendoUsado) {
                        try {
                            Thread.sleep(5000);
                            System.out.println("== Aguardando timeSeriesSerUsado keyEvent==");


                        } catch (InterruptedException ex) {
                            Logger.getLogger(ProgramaGraficos.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                    timeSeriesSendoUsado = true;
                    gerarTimeSeriesMes();
                    timeSeriesSendoUsado = false;
                    corrente = true;
                    potencia = false;
                    moeda = false;
                } else if (!corrente && !potencia && moeda && !mes && dia && !hora && !minuto) {
                    demo.setVisible(false);
                    while (timeSeriesSendoUsado) {
                        try {
                            Thread.sleep(5000);
                            System.out.println("== Aguardando timeSeriesSerUsado keyEvent==");


                        } catch (InterruptedException ex) {
                            Logger.getLogger(ProgramaGraficos.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                    timeSeriesSendoUsado = true;
                    try {
                        gerarTimeSeriesDiaKw();
                    } catch (SQLException ex) {
                        Logger.getLogger(ProgramaGraficos.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    timeSeriesSendoUsado = false;
                    corrente = false;
                    potencia = true;
                    moeda = false;
                } else if (!corrente && potencia && !moeda && !mes && dia && !hora && !minuto) {
                    demo.setVisible(false);
                    while (timeSeriesSendoUsado) {
                        try {
                            Thread.sleep(5000);
                            System.out.println("== Aguardando timeSeriesSerUsado keyEvent==");


                        } catch (InterruptedException ex) {
                            Logger.getLogger(ProgramaGraficos.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                    timeSeriesSendoUsado = true;
                    try {
                        gerarTimeSeresDias();
                    } catch (SQLException ex) {
                        Logger.getLogger(ProgramaGraficos.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    timeSeriesSendoUsado = false;
                    corrente = true;
                    potencia = false;
                    moeda = false;
                } else if (!corrente && !potencia && moeda && !mes && !dia && hora && !minuto) {
                    demo.setVisible(false);
                    while (timeSeriesSendoUsado) {
                        try {
                            Thread.sleep(5000);
                            System.out.println("== Aguardando timeSeriesSerUsado keyEvent==");


                        } catch (InterruptedException ex) {
                            Logger.getLogger(ProgramaGraficos.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                    timeSeriesSendoUsado = true;
                    try {
                        gerarTimeSeriesHoraKw();
                    } catch (SQLException ex) {
                        Logger.getLogger(ProgramaGraficos.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    timeSeriesSendoUsado = false;
                    corrente = false;
                    potencia = true;
                    moeda = false;
                } else if (!corrente && potencia && !moeda && !mes && !dia && hora && !minuto) {
                    demo.setVisible(false);
                    while (timeSeriesSendoUsado) {
                        try {
                            Thread.sleep(5000);
                            System.out.println("== Aguardando timeSeriesSerUsado keyEvent==");


                        } catch (InterruptedException ex) {
                            Logger.getLogger(ProgramaGraficos.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                    timeSeriesSendoUsado = true;
                    gerarTimeSeriesHoras();
                    timeSeriesSendoUsado = false;
                    corrente = true;
                    potencia = false;
                    moeda = false;
                }
                break;
            default:
                break;
        }
    }

    public synchronized void setTimeSeriesSendoUsado(boolean b) {
        timeSeriesSendoUsado = b;
    }
}
